import { defineConfig, loadEnv } from 'vite'
import createVuePlugin from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import Icons from 'unplugin-icons/vite'
import topLevelAwait from 'vite-plugin-top-level-await'
import { fileURLToPath, URL } from 'url'

export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
  const root = process.cwd()
  const { VITE_APP_PROXY } = loadEnv(mode, root)

  return {
    build: {
      sourcemap: true
    },
    plugins: [
      createVuePlugin(),
      vueJsx(),
      topLevelAwait({
        // The export name of top-level await promise for each chunk module
        promiseExportName: '__tla',
        // The function to generate import names of top-level await promise in each chunk module
        promiseImportName: (i) => `__tla_${i}`
      }),
      AutoImport({
        imports: ['vue', 'vue-router', 'vue-i18n']
      }),

      Icons({
        autoInstall: true
      })
    ],
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
      alias: [
        {
          find: '@',
          replacement: fileURLToPath(new URL('./src', import.meta.url))
        },
        {
          find: 'static',
          replacement: fileURLToPath(
            new URL('./public/static', import.meta.url)
          )
        }
      ]
    },
    server: {
      proxy: {
        '/api': {
          secure: false,
          target: VITE_APP_PROXY,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^/api`), '')
        }
      }
    }
  }
})
